<template>
  <div v-if="showSelectorPopup" >
    <van-popup v-model="showSelectorPopup" class="lc-fullscreen-popup" position="bottom" @click-overlay="clickOverlay">
      <!-- 头部 -->
      <van-nav-bar
        :left-text="leftText"
        left-arrow
        @click-left="onCancel"
      >
        <span slot="title" @click="onTitle()">{{ title }}</span>
        <span slot="right" class="van-nav-bar__text" @click="onConfirm" >{{ $t('confirm') }}</span>
      </van-nav-bar>
      <div class="lc-fixed-navbar">
        <!-- 搜索框 -->
        <form action="/">
          <van-search
            v-model="search"
            :placeholder="searchPlaceholder"
            @search="onSearchAction"
          >
            <!-- <van-icon slot="action" name="wap-nav" style="padding:0 10px;" @click="onSearchAction"/> -->
          </van-search>
        </form>

        <!-- 组织 -->
        <van-cell-group>
          <!-- <van-cell is-link>
                <div slot="title">
                    按成员名称选人
                </div>
          </van-cell> -->
          <van-cell class="root-title">
            <div slot="title">
              <template v-for="(data,index) in pathData" >
                <span
                  :key="data[valueKey]"
                  :class="{'is-link':pathData.length-1!==index}"
                  @click="changePath(index)">{{ data[labelKey] }}</span>
                <span v-if="pathData.length-1!==index" :key="index">/</span>
              </template>
            </div>
          </van-cell>
          <van-cell
            v-for="(data,index) in orgList"
            :key="data[idKey]+index"
            clickable
            class="root-content"
            @click="toggleChild(data,index)"
          >
            <div slot="title">{{ data[labelKey] }}</div>
            <span
              v-if="data.hasChild"
              slot="right-icon"
            >
              <span class="van-cell__right-icon">下级</span>
              <van-icon name="arrow " class="van-cell__right-icon" />
            </span>
          </van-cell>
        </van-cell-group>

        <!-- 列表内容 start -->
        <!---多选-->
        <van-checkbox-group v-if="multiple" v-model="checkbox">
          <van-cell-group>
            <van-list v-model="loading" :finished="finished" @load="onLoad">
              <van-cell
                v-for="(data,index) in dataList"
                :key="data[valueKey]+index"
                clickable
                @click="toggle(data,index)"
              >
                <van-checkbox
                  slot="icon"
                  ref="checkboxes"
                  :name="data[valueKey]"
                  style=" margin-top: 15px;"/>
                <template slot="title" >
                  <lc-card
                    :image="getPhoto(data['photo'])"
                    :text ="data[labelKey]"
                    :title="data[labelKey]"
                    bg-color="#3598dc"
                    circle
                    size="40"
                  />
                </template>
              </van-cell>
            </van-list>
          </van-cell-group>
        </van-checkbox-group>

        <!---单选-->
        <van-radio-group v-else v-model="radio" >
          <van-cell-group>
            <van-list v-model="loading" :finished="finished" @load="onLoad">
              <van-cell
                v-for="(data,index) in dataList"
                :key="data[valueKey]+index"
                clickable
                @click="toggle(data,index)"
              >
                <van-radio
                  slot="icon"
                  ref="radioes"
                  :name="data[valueKey]"
                  style=" margin-top: 15px;"/>
                <template slot="title" >
                  <lc-card
                    :image="getPhoto(data['photo'])"
                    :text ="data[labelKey]"
                    :title="data[labelKey]"
                    bg-color="#3598dc"
                    circle
                    size="40"
                  />
                </template>
              </van-cell>
            </van-list>
          </van-cell-group>
        </van-radio-group>
        <!-- 列表内容 end -->
      </div>
    </van-popup>
    <!--点击明细 -->
    <van-popup v-model="showDetailPopup" class="lc-fullscreen-popup" position="right">
      <van-nav-bar
        :left-text="leftText"
        left-arrow
        @click-left="onDetailCancel"
      >
        <span slot="title">已选择的选项</span>
        <span slot="right" class="van-nav-bar__text" @click="onDetailConfirm" >{{ $t('confirm') }}</span>
      </van-nav-bar>
      <div class="lc-fixed-navbar">
        <van-cell-group>
          <van-swipe-cell
            v-for="(data,index) in selectedData"
            :key="data[valueKey]+index"
            :right-width="65"
            class="lc-swipe-cell" >
            <van-cell
              clickable
            >
              <template slot="title" >
                <lc-card
                  :image="getPhoto(data['photo'])"
                  :text ="data[labelKey]"
                  :title="data[labelKey]"
                  bg-color="#3598dc"
                  circle
                  size="40"
                />
              </template>
            </van-cell>
            <span slot="right" @click="removeSelected(index)" >{{ $t('delete') }}</span>
          </van-swipe-cell>
        </van-cell-group>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { getUserById, queryByOrgIdOrName } from '@/api/platform/org/employee'
import { queryByParentIdOrName } from '@/api/platform/org/org'
import { formatParams, loadFinished, getResultType } from '@/utils/params'
import LcCard from '@/components/LcCard'
import i18n from '@/lang' // Internationalization 国际化
export default {
  components: {
    LcCard
  },
  props: {
    showPopup: Boolean,
    multiple: Boolean,
    value: {
      type: [String, Array]
    },
    leftText: {
      type: String,
      default: i18n.t('cancel')
    },
    searchPlaceholder: {
      type: String,
      default: i18n.t('common.input')
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    idKey: {
      type: String,
      default: 'id'
    },
    parentIdKey: {
      type: String,
      default: 'parentId'
    },
    childrenKey: {
      type: String,
      default: 'children'
    }
  },
  data() {
    return {
      search: '',
      page: 1,
      loading: false,
      finished: false,
      isLoading: true,
      resultType: 'init',
      errorType: null,
      resultMessage: null,
      pathData: [],
      radio: '',
      checkbox: [],
      orgList: [],
      dataList: [],
      cacheData: {},
      showSelectorPopup: false,
      showDetailPopup: false
    }
  },
  computed: {
    title() {
      if (this.multiple) {
        const length = this.checkbox.length
        return length > 0 ? i18n.t('components.checkbox.title', { length: length }) : ''
      } else {
        return this.$utils.isNotEmpty(this.radio) ? this.cacheData[this.radio] ? this.cacheData[this.radio][this.labelKey] : '' : ''
      }
    },
    selectedData() {
      return this.checkbox.map((d) => {
        return this.cacheData[d] || {}
      })
    }
  },
  watch: {
    value() {
      this.initData(this.value)
    },
    showPopup() {
      this.showSelectorPopup = this.showPopup
      if (this.showPopup) {
        this.search = ''
        this.initPageData()
        this.loadData({
          name: '组织架构'
        }, true)
      } else {
        this.radio = ''
        this.checkbox = []
      }
    }
  },
  methods: {
    onLoad() {
      const params = {}
      const pathData = this.pathData
      if (this.search) {
        params['name'] = this.search
      }
      if (pathData.length > 1 && pathData[pathData.length - 1]) {
        params['orgId'] = pathData[pathData.length - 1].id
      }
      this.loadUserData(params)
    },
    initData(data) {
      this.checkedValue = []
      if (this.$utils.isEmpty(data)) {
        return
      }
      data.forEach(v => {
        if (this.cacheData[v]) {
          this.checkedValue.push(v)
        } else {
          this.getDataInfo(v)
        }
      })
      if (this.multiple) {
        this.checkbox = data
      } else {
        this.radio = data[0]
      }
    },
    /**
     * 获取数据信息
     */
    getDataInfo(id) {
      getUserById({ id: id }).then(response => {
        const data = response.data
        data[this.labelKey] = data['fullname']
        this.cacheData[data[this.idKey]] = data
        this.checkedValue.push(data[this.idKey])
        this.$emit('init-data', this.getSelectedData(this.checkedValue))
      }).catch((e) => {
        console.error(e)
      })
    },
    loadData(data, isInit) {
      if (isInit) {
        this.pathData = []
      }
      const parentId = data[this.idKey] || '0'
      // 加载
      const params = { parentId: parentId }
      queryByParentIdOrName(formatParams(params)).then(res => {
        this.orgList = res.data.dataResult

        data[this.childrenKey] = this.orgList
        this.pathData.push(data)
        if (parentId === '0' || parentId === 0) {
          this.loadUserData(null)
        } else {
          this.loadUserData({ 'orgId': data[this.idKey] })
        }
      }).catch((e) => {
        console.error(e)
      })
    },
    // 加载用户数据
    loadUserData(params) {
      queryByOrgIdOrName(formatParams(params, { 'page': this.page })).then(response => {
        const dataList = response.data.dataResult

        if (this.$utils.isNotEmpty(dataList)) {
          dataList.map((d) => {
            d[this.labelKey] = d[this.labelKey]
            this.cacheData[d[this.valueKey]] = d
          })
          this.page++
          this.dataList = this.dataList.concat(dataList)
          this.finished = false
        }
        this.finished = !!loadFinished(response.data.pageResult)
        this.loading = false
        this.isLoading = false
        // 结果类型
        this.resultType = getResultType(this.list, this.finished)
      }).catch((e) => {
        this.loading = false
        this.isLoading = false
        this.finished = true
        this.resultType = 'error'
        this.resultMessage = e.message
        console.error(e)
      })
    },
    getSelectedData(data) {
      return data.map((d) => {
        return this.cacheData[d]
      })
    },
    onCancel() {
      this.$emit('cancel')
    },
    onConfirm() {
      const data = this.multiple ? this.checkbox : [this.radio]
      this.$emit('confirm', this.getSelectedData(data))
    },
    clickOverlay() {
      this.$emit('click-overlay')
    },
    toggleChild(data) {
      this.initPageData()
      this.loadData(data)
    },
    changePath(index) {
      const parentOrg = this.pathData[index]
      this.orgList = parentOrg[this.childrenKey]
      this.pathData.splice(index + 1, this.pathData.length - 1)
      this.page = 1
      this.dataList = []
      this.loadUserData({
        orgId: parentOrg[this.idKey]
      })
    },
    // 查询
    onSearchAction() {
      this.initPageData()
      this.loadUserData({ 'name': this.search })
    },
    onDetailCancel() {
      this.showDetailPopup = false
    },
    onDetailConfirm() {
      this.showDetailPopup = false
    },
    onTitle() {
      if (!this.multiple) { return }
      this.showDetailPopup = true
    },
    getPhoto(photo) {
      if (this.$utils.isNotEmpty(photo)) {
        return photo.split('=')[1]
      } else {
        return
      }
    },
    toggle(data, index) {
      if (this.multiple) { // 多选
        this.toggleCheckbox(data, index)
      } else {
        this.toggleRadio(data, index)
      }
    },
    // 单选
    toggleRadio(data, index) {
      this.radio = data[this.valueKey]
    },
    toggleCheckbox(data, index) {
      this.$refs.checkboxes[index].toggle()
    },
    removeSelected(index) {
      this.checkbox.splice(index, 1)
    },
    initPageData() {
      this.page = 1
      this.dataList = []
      this.orgList = []
      this.cacheData = []
    }
  }
}
</script>
